import 'dart:io' show File;

import 'package:flutter_app/utils/path_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/manager/UserInfoManager.dart';
import 'package:flutter_app/r.dart';
import 'package:flutter_app/utils/date_time_utils.dart';
import 'package:flutter_app/utils/image_file_info_utils.dart';
import 'package:flutter_app/utils/video_compress_utils.dart';
import 'package:flutter_app/values/MyColors.dart';
import 'package:flutter_app/widget/gallery/gallery.dart';
import 'package:flutter_app/widget/picker/camera_utils.dart';
import 'package:flutter_screenutil/src/size_extension.dart';
import 'package:get/get.dart';
import 'package:image_pickers/image_pickers.dart';

import '../collect_detail_logic.dart';

/**
 * @Description: 横向图片选择
 * @Author: 下雨了
 * @CreateDate: 2022-07-04 16:06
 * @UpdateUser: 更新者
 * @UpdateDate:  2022-07-04 16:06
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
///

/// 自定义结果回调
typedef OnMediaResultsCallback = void Function(List<Media> imagesList);

final GlobalKey<_HorizontalImagePageState> horizontalImageKey = new GlobalKey();

class HorizontalImagePage extends StatefulWidget {
  /// 文件保存的路径
  final String dirName;

  /// 带过来的本地图片
  final List<Media> resultList;

  /// 自定义结果回调
  final OnMediaResultsCallback? onMediaResultsCallback;

  const HorizontalImagePage({
    Key? key,
    required this.dirName,
    required this.resultList,
    this.onMediaResultsCallback,
  }) : super(key: key);

  @override
  _HorizontalImagePageState createState() => _HorizontalImagePageState();
}


class _HorizontalImagePageState extends State<HorizontalImagePage> {
  final logic = Get.find<CollectDetailLogic>();

  // 存放本地选择图片和视频的 list
  List<Media> resultList = [];

  var itemWidth = 80.r;

  // 重新加载 刷新数据
  void update() {
    setState(() {
      resultList = widget.resultList;
    });
  }

  @override
  void initState() {
    super.initState();
    // 本地图片
    if (widget.resultList.length > 0) {
      resultList = widget.resultList;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 0, right: 0, top: 0),
      width: Get.width,
      height: itemWidth,
      child: GridView(
        padding: EdgeInsets.only(top: 0),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1,
          mainAxisSpacing: 7.5.r,
        ),
        scrollDirection: Axis.horizontal,
        children: buildItems(),
      ),
    );
  }

  // 生成GridView的items
  List<Widget> buildItems() {
    List<Widget> items = [];

    // 添加 + 号 按钮
    items.add(pickerImageButton());

    // 添加本地资源
    if (resultList.length > 0) {
      for (int i = 0; i < resultList.length; i++) {
        if (i < 2) {
          items.add(ImageItem(resultList[i], i));
        }
        if (i == 2) {
          items.add(ImageItem(resultList[i], resultList.length));
          break;
        }
      }
    }
    return items;
  }

  // + 号 item视图
  Widget pickerImageButton() {
    return GestureDetector(
        onTap: loadImages,
        behavior: HitTestBehavior.opaque,
        child: Container(
          width: itemWidth,
          height: itemWidth,
          color: Colors.black12,
          child: Image.asset(R.assetsImgIcon72),
        ));
  }

  // 显示图片
  // 基础展示的item 此处设置width,height对GridView 无效，主要是偷懒给feedback用
  Widget ImageItem(Media media, int index) {
    return GestureDetector(
      child: Container(
        width: itemWidth,
        height: itemWidth,
        child: Stack(
          children: [
            media.galleryMode == GalleryMode.image
            ? Image.file(
              File(media.path ?? ""),
              fit: BoxFit.cover,
              width: itemWidth,
            )
            : Image.file(
              File(media.thumbPath ?? ""),
              fit: BoxFit.cover,
              width: itemWidth,
            ),
            Visibility(
              visible: media.galleryMode == GalleryMode.video,
              child: Center(
                child: Image.asset(R.assetsImgIcon57, width: 30.r,),
              ),
            ),
            Visibility(
              visible: index >= 2,
              child: Container(
                width: itemWidth,
                height: itemWidth,
                color: Colors.black26,
                alignment: Alignment.center,
                child: Text("+$index", style: TextStyle(color: MyColors.FFFFFFFF, fontSize: 16.sp),),
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        if (index < 2) {
          List<GalleryModel> list = [];
          resultList.forEach((element) {
            list.add(GalleryModel(
                id: element.path ?? "",
                url: element.path ?? "",
                time: element.dateTime,
                address: element.address,
            ));
          });
          gallery(list, showIndex: index);
        } else {
          logic.goToPhotoGalleryPage();
        }
      },
    );
  }

  /// 点击 添加 加载图片
  Future<void> loadImages() async {

    Media? media = await CameraUtils().openCameraAddWatermark(dirName: widget.dirName);
    // Media? media = await CameraUtils().openCamera(dirName: widget.dirName);
    if (media != null) {
      setState(() {
        resultList.add(media);
        widget.onMediaResultsCallback?.call(resultList);
        upMediaData(media);
      });
    }
  }

  /// 变更 存放选择图片的 list 之后，都要进行回调，来刷新回调的值
  Future upMediaData(Media media) async {
    List<ImageFileInfo> info = [];
    ImageFileInfo bean = new ImageFileInfo();
    bean.groupId = widget.dirName;
    bean.photographer = UserInfoManager().getUserName();
    File file = File(media.path!);

    int milliseconds = int.parse(PathUtils.getNameWithoutExtension(file.path));
    bean.name = PathUtils.getName(file.path);
    bean.path = media.path;

    if (media.galleryMode == GalleryMode.image) {
      bean.type = "image";
      bean.thumbnail = media.path;
    } else {
      bean.type = "video";
      bean.thumbnail = media.thumbPath;
      bean.duration = await VideoCompressUtils().getVideoDuration(media.path ?? "");
    }
    // 时间戳毫秒 转换成 DateTime
    DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(milliseconds);
    // 转换成特定的格式
    bean.time = DateTimeUtils.formZone(dateTime);
    bean.address = media.address;
    bean.dateTime = media.dateTime;
    info.add(bean);

    await ImageFileInfoUtils().addItem(info);
  }

  @override
  void dispose() {
    super.dispose();
  }
}